#!/usr/bin/python
# -*- encoding: utf-8 -*-
#from codecs import ignore_errors
import pexpect
import re
import time
from common.basetest import LocalTest
"""
@File:      tc_ag_util-linux_fdisk_002.py
@Time:      2022/06/20 11:12:50
@Author:    zhangtaibo
@Version:   1.0
@Contact:   zhangtaibo.ztb@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    liangjian
"""

def fdisk_add(self):
    ret_c, self.dev = self.cmd("fdisk -l |head -1 |awk '{print $2}'")
    self.dev = self.dev.strip(":")
    ret_c, self.os_ver = self.cmd("cat /etc/os-release |grep \"PRETTY_NAME\" |awk -F \"=\" '{print $2}'")
    self.os_ver = eval(self.os_ver)
    child = pexpect.spawn('fdisk %s' % (self.dev))
    child.expect(['Command'],timeout=2)
    child.sendline('n')
    if self.os_ver == "Anolis OS 23":
        child.expect(['default'],timeout=2)
        str_out =child.before.decode()
        self.dev_num = re.findall(r".*\((.*)\-",str_out)
        print(self.dev_num)
        child.sendline('')
        child.sendline('')
    else:
        child.expect(['default'],timeout=2)
        str_out =child.before.decode()
        self.dev_num =re.findall('(\d+)',str_out)
        print(self.dev_num[0])
        child.sendline('')
        child.expect(['First'])
        if int(self.dev_num[0]) == 1:
            child.sendline('')
        else:
            ret_c, self.start_size = self.cmd("fdisk -l %s |tail -n -1|awk -F \" \" '{print $3}'" % self.dev)
            print(self.start_size)
            start_size = int(self.start_size) + 1
            print(start_size)
            child.sendline('%s' % (start_size))
    child.sendline('')
    index = child.expect([pexpect.TIMEOUT,'remove the signature'],timeout=2)
    if index == 1:
         child.sendline('y')
    child.sendline('w')
    child.sendline('q')
    cmd = self.dev + str(self.dev_num[0])
    ret_c, ret_o = self.cmd("fdisk -l %s" % (cmd),ignore_status=True)
    return ret_c
def fdisk_del(self):
    child = pexpect.spawn('fdisk %s' % (self.dev))
    child.expect(['Command'],timeout=2)
    child.sendline('d')
    child.sendline('%s'% (self.dev_num[0]))
    child.sendline('w')
    child.sendline('q')
    cmd = self.dev + str(self.dev_num[0])
    ret_c, ret_o = self.cmd("fdisk -l %s" % cmd,ignore_status=True)
    return ret_c

def fdisk_help(self):
    child = pexpect.spawn('fdisk %s' % (self.dev))
    child.expect(['Command'],timeout=2)
    child.sendline('m')
    child.expect(['Help'],timeout=2)
    child.sendline('q')

def fdisk_space(self):
    ret_c, self.dev = self.cmd("fdisk -l |head -1 |awk -F \" \" '{printf $2}'")
    self.dev = self.dev.strip(":")
    child = pexpect.spawn('fdisk %s' % (self.dev))
    child.sendline('n')
    index = child.expect([pexpect.TIMEOUT,'is in use'],timeout=2)
    return index

def script_fun():
    cmd = "script -t 2>hello.time -a hello.txt"
    child = pexpect.spawn("/bin/bash", ["-c", cmd])
    child.sendline('echo hello')
    child.expect(['hello'],timeout=2)
    child.sendline('exit')

